package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TodayBestService {

    @Autowired
    private UserService userService;

    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private UserInfoService userInfoService;

    @Value("${tanhua.sso.default.user}")
    private Long defaultUser;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PicUploadService picUploadService;



    public TodayBest queryTodayBest(/*String token*/) {
        //校验token是否有效，通过sso的接口进行校验
        /*User user = userService.queryUserByToken(token);
        if (null == user) {
            //token非法或已经过期
            return null;
        }*/
        //直接从ThreadLocal获取user
        User user = UserThreadLocal.get();

        //2.关联dubbo服务查询推荐用户 - 查询推荐用户(今日佳人)
        TodayBest todayBest = recommendUserService.queryTodayBest(user.getId());

        //3.构建返回用户【TodayBest】基础信息
        if(todayBest == null){
            //3.1 如果查询结果为空，给出默认的推荐用户
            todayBest = new TodayBest();
            todayBest.setId(defaultUser);   //默认id - 2
            todayBest.setFateValue(80L);    //缘分值
        }

        //3.2 补全个人信息，调用userInfoService连接mysql进行查询 - todayBest一定是有id的，还有缘分值
        UserInfo userInfo = userInfoService.queryUserInfoByUserId(todayBest.getId());
        if(userInfo == null){
            return null;
        }

        //3.3 将查询结果，构建到TodayBest对象中
        todayBest.setAvatar(userInfo.getLogo());        //头像
        todayBest.setNickname(userInfo.getNickName());  //昵称
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));  //标签
        todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");     //性别
        todayBest.setAge(userInfo.getAge());            //年龄

        return todayBest;
    }


    /**
     * 查询推荐用户列表
     *
     * @param queryParam
     * //@param token
     * @return
     */
    public PageResult queryRecommendation(/*String token,*/ RecommendUserQueryParam queryParam) {
        //校验token是否有效，通过sso的接口进行校验
        /*User user = userService.queryUserByToken(token);
        if (null == user) {
            //token非法或已经过期
            return null;
        }*/

        //直接从ThreadLocal获取user
        User user = UserThreadLocal.get();

        //【构建返回结果信息 - PageResult】
        PageResult pageResult = new PageResult();


        //2.关联dubbo服务查询推荐用户 - 查询推荐用户(列表)
        PageInfo<RecommendUser> pageInfo = recommendUserService.queryRecommendUserList(user.getId(), queryParam.getPage(), queryParam.getPagesize());
        //2.1 获取dubbo服务提供分页PageInfo对象中的结构数据，该数据泛型是RecommendUser，里面只包含推荐的 用户id，和缘分值
        List<RecommendUser> records = pageInfo.getRecords();
        //2.2 非空判断
        if (CollectionUtils.isEmpty(records)) {
            //没有查询到推荐的用户列表
            return pageResult;
        }

        //2.3 证明可以查询到推荐用户信息列表

        //3.构建返回用户【TodayBest】基础信息

        //3.1 构建推荐用户的id的set集合 - 构建查询条件
        Set<Long> userIds = new HashSet<>();    //1,2,3...
        //3.2 遍历推荐用户列表，获取每个推荐用户id，保存到set集合中
        for (RecommendUser record : records) {
            userIds.add(record.getUserId());
        }

        //3.3 构造查询条件
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();

        //3.3.1 用户id参数
        queryWrapper.in("user_id", userIds);                // where user_id in (?,?...)

        //3.3.2 构建除id以外所有条件
        if (StringUtils.isNotEmpty(queryParam.getGender())) {       // and sex = ?
            //需要性别参数查询
            //queryWrapper.eq("sex", StringUtils.equals(queryParam.getGender(), "man") ? 1 : 2);
        }

        if (StringUtils.isNotEmpty(queryParam.getCity())) {         // and city like ?
            //需要城市参数查询
            //queryWrapper.like("city", queryParam.getCity());
        }

        if (queryParam.getAge() != null) {                          // and age < ?
            //设置年龄参数，条件：小于等于
            //queryWrapper.le("age", queryParam.getAge());
        }

        //3.4 调用userInfoService，根据条件查询用户相关完整信息
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(queryWrapper);

        //3.5 非空判断
        if(CollectionUtils.isEmpty(userInfoList)){
            //没有查询到用户的基本信息
            return pageResult;
        }


        //4.封装最终返回的数据信息
        List<TodayBest> todayBests = new ArrayList<>();
        //4.1 遍历查询到的用户详情信息
        for (UserInfo userInfo : userInfoList) {
            //4.2 每有一个推荐用户，就封装一个TodayBest对象
            TodayBest todayBest = new TodayBest();

            //4.3 构建TodayBest基础信息
            todayBest.setId(userInfo.getUserId());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
            todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
            todayBest.setAge(userInfo.getAge());

            //4.4 缘分值
            //4.4.1 遍历推荐用户集合，获取每个用户缘分值
            for (RecommendUser record : records) {
                //4.4.2 判断遍历出来推荐用户id  == 查询到并遍历每个userInfo对象id
                if(record.getUserId().longValue() == userInfo.getUserId().longValue()){
                    //4.4.3 设置缘分值
                    double score = Math.floor(record.getScore());//取整,98.2 -> 98
                    todayBest.setFateValue(Double.valueOf(score).longValue());
                    break;
                }
            }

            //4.5 将完整的TodayBest信息添加到集合中
            todayBests.add(todayBest);
        }

        //按照缘分值进行倒序排序
        Collections.sort(todayBests, (o1, o2) -> new Long(o2.getFateValue() - o1.getFateValue()).intValue());

        /*Collections.sort(todayBests, new Comparator<TodayBest>() {
            @Override
            public int compare(TodayBest o1, TodayBest o2) {
                return new Long(o2.getFateValue() - o1.getFateValue()).intValue();
            }
        });*/


        //5.最终构建PageResult返回值
        pageResult.setPage(queryParam.getPage());           //将请求参数中当前页码page构建到PageResult中
        pageResult.setPagesize(queryParam.getPagesize());   //将请求参数中每页条数pagesize构建到PageResult中
        pageResult.setItems(todayBests);                    //将TodayBest集合添加到最终返回PageResult的item属性数据列表上

        return pageResult;
    }

}
